
<template>
  <div class="app-container">
    <!-- 群发消息表单 -->
    <el-card class="box-card" style="margin-bottom: 20px;">
      <div slot="header" class="clearfix">
        <span>群发消息</span>
      </div>
      
      <el-form :model="messageForm" ref="messageForm" :rules="messageRules" label-width="100px">
        <!-- 选择群组 -->
        <el-form-item label="选择群组" prop="groupIds">
          <el-select 
            v-model="messageForm.groupIds" 
            multiple 
            placeholder="请选择要发送的群组"
            style="width: 100%;"
            filterable
            remote
            :remote-method="searchGroups"
            :loading="groupLoading"
            @focus="loadGroups"
            @visible-change="handleSelectVisibleChange"
          >
            <el-option
              v-for="group in groupList"
              :key="group.id"
              :label="group.name"
              :value="group.id"
            >
              <span style="float: left">{{ group.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">ID: {{ group.id }}</span>
            </el-option>
            <el-option
              v-if="groupHasMore && !groupLoading"
              :value="'load-more'"
              disabled
              style="text-align: center; color: #409EFF; cursor: pointer;"
              @click.native="loadMoreGroups"
            >
              点击加载更多...
            </el-option>
            <el-option
              v-if="groupLoading"
              :value="'loading'"
              disabled
              style="text-align: center;"
            >
              加载中...
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 消息内容 -->
        <el-form-item label="消息内容" prop="content">
          <el-input
            v-model="messageForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入要发送的消息内容"
            maxlength="500"
            show-word-limit
          ></el-input>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="sendMessage" :loading="sending">发送消息</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 发送历史记录 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>发送历史</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="refreshHistory">刷新</el-button>
      </div>

      <el-table v-loading="loading" :data="historyList" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="groupNames" label="发送群组" min-width="200">
          <template slot-scope="scope">
            <el-tag v-for="name in scope.row.groupNames" :key="name" size="mini" style="margin-right: 5px;">{{ name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="消息内容" min-width="300" show-overflow-tooltip></el-table-column>
        <el-table-column prop="sendTime" label="发送时间" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.sendTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 'success' ? 'success' : 'danger'">
              {{ scope.row.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="historyTotal > 0"
        :total="historyTotal"
        :page.sync="historyQuery.pageNum"
        :limit.sync="historyQuery.pageSize"
        @pagination="getHistory"
      />
    </el-card>
  </div>
</template>

<script>
import {sendGroupMessage, groupMessageList } from "@/api/zl/messages"
import { listGroup } from "@/api/zl/group"

export default {
  name: "GroupMessages",
  data() {
    return {
      // 发送表单
      messageForm: {
        groupIds: [],
        content: ''
      },
      // 表单验证规则
      messageRules: {
        groupIds: [
          { required: true, message: "请选择要发送的群组", trigger: "change" }
        ],
        content: [
          { required: true, message: "请输入消息内容", trigger: "blur" },
          { min: 1, max: 500, message: "消息内容长度在 1 到 500 个字符", trigger: "blur" }
        ]
      },
      // 群组列表
      groupList: [],
      // 群组分页相关
      groupLoading: false,
      groupPageNum: 1,
      groupPageSize: 20,
      groupTotal: 0,
      groupHasMore: true,
      groupSearchKeyword: '',
      // 发送状态
      sending: false,
      // 历史记录
      loading: false,
      historyList: [],
      historyTotal: 0,
      historyQuery: {
        pageNum: 1,
        pageSize: 10
      }
    }
  },
  created() {
    this.loadGroups()
    this.getHistory()
  },
  methods: {
    // 加载群组列表
    async loadGroups(reset = true) {
      if (this.groupLoading) return
      
      try {
        this.groupLoading = true
        
        if (reset) {
          this.groupPageNum = 1
          this.groupList = []
          this.groupHasMore = true
        }
        
        const queryParams = {
          pageNum: this.groupPageNum,
          pageSize: this.groupPageSize
        }
        
        // 如果有搜索关键词，添加到查询参数
        if (this.groupSearchKeyword) {
          queryParams.name = this.groupSearchKeyword
        }
        
        const response = await listGroup(queryParams)
        
        // 根据后端返回的数据结构调整字段映射
        const newGroups = response.rows.map(group => ({
          id: group.gid || group.id, // 使用gid作为群组ID
          name: group.name || `群组${group.gid}` // 使用name作为群组名称
        }))
        
        if (reset) {
          this.groupList = newGroups
        } else {
          this.groupList = [...this.groupList, ...newGroups]
        }
        
        this.groupTotal = response.total || 0
        this.groupHasMore = this.groupList.length < this.groupTotal
        
      } catch (error) {
        console.error('加载群组列表失败:', error)
        this.$modal.msgError('加载群组列表失败')
        // 如果API调用失败，使用空数组
        if (reset) {
          this.groupList = []
        }
      } finally {
        this.groupLoading = false
      }
    },
    
    // 加载更多群组
    async loadMoreGroups() {
      if (!this.groupHasMore || this.groupLoading) return
      
      this.groupPageNum++
      await this.loadGroups(false)
    },
    
    // 搜索群组
    async searchGroups(keyword) {
      this.groupSearchKeyword = keyword
      await this.loadGroups(true)
    },
    
    // 处理下拉框显示状态变化
    handleSelectVisibleChange(visible) {
      if (visible) {
        // 下拉框打开时，如果没有数据则加载
        if (this.groupList.length === 0) {
          this.loadGroups(true)
        }
      }
    },
    
    // 发送消息
    async sendMessage() {
      this.$refs['messageForm'].validate(async (valid) => {
        if (valid) {
          this.sending = true
          try {
            // 构造发送数据 - 根据后端 GroupSendMessage DTO 调整
            const sendData = {
              ids: this.messageForm.groupIds.map(id => String(id)), // 转换为字符串数组
              text: this.messageForm.content // 消息内容
            }
            
            await sendGroupMessage(sendData)
            this.$modal.msgSuccess('消息发送成功')
            this.resetForm()
            this.getHistory() // 刷新历史记录
          } catch (error) {
            this.$modal.msgError('消息发送失败')
          } finally {
            this.sending = false
          }
        }
      })
    },
    
    // 重置表单
    resetForm() {
      this.$refs['messageForm'].resetFields()
      this.messageForm = {
        groupIds: [],
        content: ''
      }
    },
    
    // 获取发送历史
    async getHistory() {
      this.loading = true
      try {
        const response = await groupMessageList(this.historyQuery)
        this.historyList = response.rows.map(item => ({
          id: item.id,
          groupNames: this.getGroupNames(item.target),
          sendTime: item.createdAt,
           content: item.content,
          status: item.status === 1 ? 'success' : 'failed' // 根据实际情况设置状态
        }))
        this.historyTotal = this.total = parseInt(response.total) || 0
      } catch (error) {
        this.$modal.msgError('加载历史记录失败')
      } finally {
        this.loading = false
      }
    },
    
    // 根据群组ID获取群组名称
    getGroupNames(targetIds) {
      if (!targetIds) return []
      const ids = targetIds.split(',')
      return ids.map(id => {
        const group = this.groupList.find(g => g.id == id)
        return group ? group.name : `群组${id}`
      })
    },
    
    // 刷新历史记录
    refreshHistory() {
      this.historyQuery.pageNum = 1
      this.getHistory()
    }
  }
}
</script>

<style scoped>
.box-card {
  margin-bottom: 20px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}
</style>
